﻿using Cosmos.App.Sdk.v1;
using Cosmos.App.Sdk.v1.Primitives;
using Cosmos.DataAccess.Trade.v1;
using Cosmos.DataAccess.Trade.v1.Protocol;
using Cosmos.DataAccess.v1;
using Cosmos.DataAccess.v1.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Cosmos.App.Hithink.ComDemo
{
    using static Cosmos.App.Hithink.ComDemo.WpfComDemoGui;
    using PushHandler = ISubscriberRaw<string, string, string, string, string, int>.PushDataHandler;

    internal class TextChange
    {
        public string text { get; set; }
    }

    /// <summary>
    /// Interaction logic for ComDemo.xaml
    /// </summary>
    public partial class ComDemo : UserControl
    {
        public ComDemo(IDataAccessor dataAccessor, ICosmosAppLogger logger, ICosmosAppContextInjection contextInjection, ITradeDataAccessor tradeDataAccessor)
        {
            InitializeComponent();
            _dataAccessor = dataAccessor;
            _tradeDataAccessor = tradeDataAccessor;
            _contextInjection = contextInjection;
            _productAccessor = contextInjection.ThisAppContext.GlobalContexts.ProductContext.ProductAccessor;

            _tradeDataAccessor.DataProvider.SubscribAppCommand((object sender, IAppRecommand pushResult) =>
            {
                string content = $"AppGuid：{pushResult.AppGuid}，AppName：{pushResult.AppName}, Content:{pushResult.Content}";
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    lab_higate.Content = content;
                }));
                
                // Console.WriteLine($"AppGuid：{pushResult.AppGuid}，AppName：{pushResult.AppName}, Content:{pushResult.Content}");
            });

            text_name.TextChanged += (sender, e) =>
            {
                // 在这里处理文本变化的逻辑
                var textBox = sender as TextBox;
                if (textBox != null)
                {
                    foreach(var kvp in dicTextChange)
                    {
                        String strUUid = kvp.Key;
                        var handle = kvp.Value;
                        if (handle != null)
                        {
                            string strSubscriberid = dicTextSub[strUUid];
                            TextChange textPush = new TextChange()
                            {
                                text = textBox.Text
                            };
                            /// 触发回调,通知订阅者文本框发生改变
                            handle(strSubscriberid, strUUid, JsonSerializer.Serialize<TextChange>(textPush));
                        }
                    }
                }
            };
        }

        public void SetWebContent(object obj)
        {
            web_demo.Content = obj;
        }

        /// <summary>
        /// 获取文本信息
        /// </summary>
        /// <returns>文本输入框内容</returns>
        public String GetText()
        {
            return text_name.Text;
        }

        /// <summary>
        /// 订阅文本变化信息
        /// </summary>
        /// <param name="pushDataHandler">订阅者回调函数</param>
        /// <returns></returns>
        public String SubscribeTextChange(string subscriberId, PushHandler pushDataHandler)
        {
            String strUUid = Guid.NewGuid().ToString();
            dicTextChange[strUUid] = pushDataHandler;
            return strUUid;
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="subscribeId">订阅时返回的uuid</param>
        public void UnSubscribeTextChange(string subscriptionId)
        {
            dicTextChange.Remove(subscriptionId);
            dicTextSub.Remove(subscriptionId);
        }
        /// <summary>
        /// 设置文本信息
        /// </summary>
        /// <param name="str">需要设置的字符串信息</param>
        public void SetText(string str)
        {
            text_name.Text = str;
        }
        private void btn_get_Click(object sender, RoutedEventArgs e)
        {
            Task.Factory.StartNew(async () =>
            {
                var queryResult = await _dataAccessor.DataProvider.QueryWatchListAsync();
                if (queryResult != null)
                {
                    String strSelfSotck = String.Join(',', queryResult.AssetIds);
                    _logger?.Log(CosmosLogLevel.Information, $"获取到自选股列表：{strSelfSotck}");
                    text_selfstock.Text = strSelfSotck;
                }
            });
        }

        /// <summary>
        /// 主动调用宿主方法，但是宿主是否处理需要宿主开发人员响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_send_msg_Click(object sender, RoutedEventArgs e)
        {
            ///获取当前实例唯一标识
            var cosmosOperator = Convert.ToString(_contextInjection.ThisInstanceContext.InstanceId);
            TextChange textInvoke = new TextChange()
            {
                text = text_name.Text
            };
            //向宿主调用comTestSetText方法,需要宿主实现该方法
            string result = await _productAccessor.InvokeAsync(cosmosOperator, "comTestSetText", JsonSerializer.Serialize<TextChange>(textInvoke));
            WpfToast.Show("发送完成");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if(String.IsNullOrEmpty(text_hotkey.Text))
            {
                WpfToast.Show("请输入快捷键", CosmosLogLevel.Warning);
                return;
            }

            var strErr = string.Empty;
            if(_contextInjection.ThisAppContext.GlobalContexts.EngineContext.BusinessRequest.ShortcutManager.AddShortcut(text_hotkey.Text, ref strErr))
            {
                WpfToast.Show("添加快捷键成功");
            }
            else
            {
                WpfToast.Show("添加快捷键失败：" + strErr, CosmosLogLevel.Error);
            }
        }


        private void btn_gettheme_Click(object sender, RoutedEventArgs e)
        {
            ///获取当前颜色主题
            var theme = _contextInjection.ThisAppContext.GlobalContexts.VisualContext.ColorScheme;
            text_theme.Text = theme.ToString();
        }

        private void btn_getthemedic_Click(object sender, RoutedEventArgs e)
        {
            ///获取当前主题的皮肤字典
            var dictionary = _contextInjection.ThisAppContext.GlobalContexts.VisualContext.ThemeResources;
            var text = JsonSerializer.Serialize(dictionary);
            text_theme.Text = dictionary.ToString();
        }

        /// <summary>
        /// 行情数据访问器
        /// </summary>
        private IDataAccessor _dataAccessor { get; set; }

        private ITradeDataAccessor _tradeDataAccessor { get; set; }


        /// <summary>
        /// 日志记录器
        /// </summary>
        private ICosmosAppLogger _logger { get; set; }

        /// <summary>
        /// 宿主访问器
        /// </summary>
        public ICosmosProductAccessor _productAccessor { get; set; }

        /// <summary>
        /// 该接口定义了当前组件和实例上下文的注入点，这些上下文在构造后由Cosmos引擎自动注入
        /// 可在该成员中实现对上下文的初始化和修改
        /// </summary>
        public ICosmosAppContextInjection _contextInjection { get; set; }

        /// <summary>
        /// 保存textchange订阅者回调函数
        /// </summary>
        private Dictionary<string, PushHandler> dicTextChange = new Dictionary<string, PushHandler>();
        private Dictionary<string, string> dicTextSub = new Dictionary<string, string>();

    }
}
